package com.nmes.naljava.server;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.Persistent;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;
import com.google.appengine.api.images.ImagesService.OutputEncoding;

import com.nmes.naljava.ImageObject;
import com.nmes.naljava.PMF;
import com.nmes.naljava.entity.Account;

@SuppressWarnings("serial")
public class ImageTransform extends HttpServlet{
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	log("ImageTransform\n");
    	String type = req.getContentType();
    	log("type:" + type + "\n");
        ServletFileUpload upload = new ServletFileUpload();
     //   upload.setSizeMax(50000000);

        Account at = new Account();
        String action = new String();
        com.google.appengine.api.datastore.Blob imageObject;

        
        com.google.appengine.api.datastore.Blob origBlob = null;
        
        PersistenceManager pm = PMF.get().getPersistenceManager();

        PrintWriter pw = null;
        try {
        	log("try\n");
            resp.reset();
            pw = resp.getWriter();
            resp.setContentType("text/html");
            
            // enctype="multipart/form-data" 를 사용해서 데이터를 보내면 request.getParameter("action") 를 사용할 수 없다.
            FileItemIterator iterator = upload.getItemIterator(req);
            while (iterator.hasNext()) 
            {
                FileItemStream item = iterator.next();
                InputStream in = item.openStream();
                BufferedInputStream bis = new BufferedInputStream(in);
                byte[] bisArray = IOUtils.toByteArray(bis);
                if( item.isFormField() == false)
                {	// 파일이므로 따로 저장한다.
                	if(bisArray.length > 0 ){
                		origBlob = new com.google.appengine.api.datastore.Blob(bisArray);
	                }
                }else
                {	// 일반 폼 데이터 
                	if(item.getFieldName().equals("id")){
                		at.setId(new Long(new String(bisArray)).longValue());
                	}
                	if(item.getFieldName().equals("action")){
                		action = new String(bisArray);
                	}
                	if(item.getFieldName().equals("title")){
                		at.setTitle(new String(bisArray));
                	}
                	if(item.getFieldName().equals("categori")){
                		at.setCategory(new String(bisArray));
                	}
                	if(item.getFieldName().equals("content")){
                		at.setContent(new String(bisArray));
                	}
                	if(item.getFieldName().equals("imageName")){
                		at.setImageName(new String(bisArray));
                	}
                	if(item.getFieldName().equals("writer")){
                		at.setWriter(new String(bisArray));
                	}
                	if(item.getFieldName().equals("rgstDate")){
                		at.setRgstDate(new String(bisArray));
                	}
                	if(item.getFieldName().equals("editDate")){
                		at.setEditDate(new String(bisArray));
                	}

                }
            }
            
            // 임시로 폼 데이터를 출력한다.
            //log( "id:" + at.getId() );
            //log( "action:" + action );
            //log( "title:" + at.getTitle() );
            //log( "categori:" + at.getCategory() );
            //log( "action:" + action );
            if( action.equals("newWriteDo"))
            {  //  새글 작성 
            	log( "newWriteDo\n" );
            	Account a = new Account(
            			at.getTitle()    // title
	                    ,at.getCategory()  //Category
	                    ,at.getContent()   //content
	                    ,at.getImageName()   //imageName  아직 이미지 이름 얻는 법을 모름
	                    ,origBlob     // file
	                    ,at.getWriter()    //writer
	                    ,at.getRgstDate()
	                    ,at.getEditDate()
	                    );
	            try {
	                pm.makePersistent(a);
	            }catch (Exception ex) {
	            	ex.printStackTrace();
	            }finally {
	                pm.close();
	            }
	            resp.sendRedirect("/SaveData?action=singleBoard&id="+ a.getId());
            }else if( action.equals("updateBoard") )
            {
            	log( "updateBoard\n" );
            	Key k = KeyFactory.createKey( Account.class.getSimpleName(), at.getId());
            	log( "k.toString():" + k.toString()+ "\n" );
            	Account a = pm.getObjectById(Account.class,k);
                try {
                	a.setTitle(at.getTitle());
                	a.setCategory (at.getCategory());
                	a.setContent(at.getContent());
                	a.setImageName(at.getImageName());
                	if( origBlob.getBytes().length > 0 ){  // 이미지는 변경이미지가 있는경우에만 저장
                		a.setImageObject(origBlob);
                	}
                	a.setWriter(at.getWriter());
                	a.setRgstDate(at.getRgstDate());
                	a.setEditDate(at.getEditDate());
                }catch (Exception ex) {
                	ex.printStackTrace();
                }finally {
                    pm.close();
                }
                
                resp.sendRedirect("/SaveData?action=singleBoard&id="+ a.getId());
                log( "end updateBoard\n");
            	
            }
            log( "end ImageTransform\n");   
            
        } catch (Exception ex) {
        	ex.printStackTrace();
        }
    }
}